#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>


using namespace std;


//TCP协议中，客户端是不用绑定端口了，绑定之后只能运行一个client的程序属于自己人为设定的， 
//而从服务器那边得到的客户机连接端口号（是系统自动分配的）与这边客户机绑定的端口号根本是不相关的，所以客户端绑定也就失去了意义。

void Usage(string proc)
{
    cout<<"Usage: "<<proc<<"server_ip  server_port"<<endl;
}


int main(int argc,char* argv[])
{

    if(argc!=3)
    {
        Usage(argv[0]);
        exit(-1);
    }

    string ip = argv[1];
    uint16_t port = stoi(argv[2]);


    //1.创建socketfd
    int socketfd = socket(AF_INET,SOCK_DGRAM,0);
    if(socketfd<0)
    {
        cerr<<"socket error"<<endl;
    }

    struct sockaddr_in addr;
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    string message;

    while(1)
    {
        cout<<"请输入：";
        getline(cin,message);
        sendto(socketfd,message.c_str(),message.size(),0,(struct sockaddr*)&addr,sizeof(addr));

        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(socketfd,buffer,sizeof(buffer),0,(struct sockaddr*)&peer,&len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "server echo# " << buffer << std::endl;
        }
    }

    return 0;
}